package util

/*
数据表排序逻辑处理工具
*/

// IndexExchange 生成序号交换修改参数列表 [执行顺序][0:查询条件,1:修改参数]map[string]interface{}
func IndexExchange(pk map[string]interface{}, a, b int, key string) [][]map[string]interface{} {
	if a == b {
		return nil
	}

	result := [][]map[string]interface{}{}

	//原位撤出 index 设为-1
	a1 := copyMap(pk)
	a1[key] = a
	a2 := map[string]interface{}{
		key: -1,
	}
	result = append(result, []map[string]interface{}{a1, a2})

	//对位移动
	b1 := copyMap(pk)
	b1[key] = b
	b2 := map[string]interface{}{
		key: a,
	}
	result = append(result, []map[string]interface{}{b1, b2})
	//原位补对位
	c1 := copyMap(pk)
	c1[key] = -1
	c2 := map[string]interface{}{
		key: b,
	}
	result = append(result, []map[string]interface{}{c1, c2})
	return result
}

// IndexMove 生成序号移动修改参数列表 [执行顺序][0:查询条件,1:修改参数]map[string]interface{}
func IndexMove(pk map[string]interface{}, from, to int, key string) [][]map[string]interface{} {
	if from == to {
		return nil
	}

	result := [][]map[string]interface{}{}

	//原位撤出 index 设为-1
	a1 := copyMap(pk)
	a1[key] = from
	a2 := map[string]interface{}{
		key: -1,
	}
	result = append(result, []map[string]interface{}{a1, a2})

	//顺位移动
	if to > from {
		for i := from + 1; i <= to; i++ {
			b1 := copyMap(pk)
			b1[key] = i
			b2 := map[string]interface{}{
				key: i - 1,
			}
			result = append(result, []map[string]interface{}{b1, b2})
		}
	} else {
		for i := from - 1; i >= to; i-- {
			b1 := copyMap(pk)
			b1[key] = i
			b2 := map[string]interface{}{
				key: i + 1,
			}
			result = append(result, []map[string]interface{}{b1, b2})
		}
	}

	//原位补齐
	c1 := copyMap(pk)
	c1[key] = -1
	c2 := map[string]interface{}{
		key: to,
	}
	result = append(result, []map[string]interface{}{c1, c2})
	return result
}

func copyMap(src map[string]interface{}) map[string]interface{} {
	m := map[string]interface{}{}
	for k, v := range src {
		m[k] = v
	}
	return m
}
